package util;

import java.sql.Connection;
import java.sql.DriverManager;

/**
 * @Author Doris.Lee
 * @Description
 * @Locate util.DBHelper
 * @Datetime 2020-05-21 07:32
 * @Version 1.0
 */
public class DBHelper {

    //私有静态格式更加严格
//    private static final String driver = "com.mysql.jdbc.Driver"; //数据库驱动
    private static final String driver = "com.mysql.cj.jdbc.Driver";


    //连接数据库的URL地址
    private static final String url="jdbc:mysql://localhost:3306/shopping?serverTimezone=CTT&useUnicode=true&characterEncoding=UTF-8";
    private static final String username="root";//数据库的用户名
    private static final String password="123456";//数据库的密码

    //连接对象
    private static Connection conn=null;

    //静态代码块负责加载驱动
    static
    {
        try
        {
            Class.forName(driver);
        }
        catch(Exception ex)
        {
            ex.printStackTrace();//异常堆栈
        }
    }

    //单例模式返回数据库连接对象
    public static Connection getConnection() throws Exception
    {
        if(conn==null)  //对象未创建
        {
            conn = DriverManager.getConnection(url, username, password);
            return conn;
        }
        return conn;
    }

    public static void main(String[] args) {

        try
        {
            Connection conn = DBHelper.getConnection();
            if(conn!=null)
            {
                System.out.println("数据库连接正常！");
            }
            else
            {
                System.out.println("数据库连接异常！");
            }
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
        }

    }
}
